package com.grape.session.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.grape.dto.OnlineUserChannelDTO;
import com.grape.session.IUserChannelStore;
import com.grape.utils.StringUtils;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@AllArgsConstructor
public class UserChannelStoreImpl implements IUserChannelStore {
    
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UserChannelStoreImpl.class);

    private static final ConcurrentHashMap<String, Channel> USER_CHANNEL = new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<String, OnlineUserChannelDTO> USER_ONLINE_DTO = new ConcurrentHashMap<>();

    public static final AttributeKey<String> USER_ID_ATTRIBUTE_KEY =
            AttributeKey.valueOf("USER_ID_ATTRIBUTE_KEY");

    /**
     * 通过用户id获取通道
     * @param userId    用户id
     * @return          通道
     */
    @Override
    public Optional<Channel> findChannelByUserId(String userId) {
        Channel channel = USER_CHANNEL.get(userId);
        return Optional.ofNullable(channel);
    }

    /**
     * 绑定用户id和通道
     *
     * @param userId  用户id
     * @param channel 通道
     * @param token 令牌
     */
    @Override
    public void bindUserToChannel(String userId, Channel channel, String token) {
        USER_CHANNEL.put(userId, channel);
        // TODO 登录类型
        USER_ONLINE_DTO.put(userId, OnlineUserChannelDTO.builder().userId(userId).lastResetTime(System.currentTimeMillis()).activeTime(System.currentTimeMillis())
//                .type(jwtUtil.getType(token))
                .build());
        channel.attr(USER_ID_ATTRIBUTE_KEY).set(userId);
    }

    /**
     * 获取所有在线用户id
     * @return  用户id
     */
    @Override
    public Set<String> getOnlineUserIds() {
        return CollectionUtil.isNotEmpty(USER_CHANNEL) ? USER_CHANNEL.keySet() : Collections.emptySet();
    }

    /**
     * 获取所有在线用户dto
     * @return  用户dto
     */
    @Override
    public List<OnlineUserChannelDTO> getOnlineUserChannelList() {
        return CollectionUtil.isNotEmpty(USER_ONLINE_DTO) ? new ArrayList<>(USER_ONLINE_DTO.values()) : Collections.emptyList();
    }

    /**
     * 更新用户上次重置时间
     * @param data  消息数据
     * @param userId    用户id
     */
    @Override
    public void updateLastResetTimeByUserId(Object data, String userId) {
        if (StringUtils.isBlank(userId)) {
            logger.error("[updateLastResetTimeByUserId] 用户id为空，更新用户上次重置时间失败");
            return;
        }
        if (!USER_ONLINE_DTO.containsKey(userId)) {
            logger.error("[updateLastResetTimeByUserId] 不存在用户id：{}的长链接，更新用户上次重置时间失败", userId);
            return;
        }
        USER_ONLINE_DTO.get(userId).setLastResetTime(System.currentTimeMillis());
    }
}
